define([
  "jquery",
  "underscore",
  "backbone",
  "../collections/todos",
  "./todos",
  "text!../../templates/stats.html",
  '../common'
], function($, _ ,Backbone, Todos, TodoView, statsTemplate, Common){
  var AppView = Backbone.View.extend({
    el: '#todoapp',
    template: _.template(statsTemplate),
    events:{
      'keypress #new-todo'    : 'createOnEnter',
      'click #clear-completed': 'clearCompleted',
      'click #toggle-all'     : 'toggleAllComplete'
    },

    initialize: function(){
      this.$input  = this.$('#new-todo');
      this.$footer = this.$('#footer');
      this.$main   = this.$('#main');

      this.listenTo(Todos, 'add', this.addOne);
      this.listenTo(Todos, 'reset', this.addAll);
      this.listenTo(Todos, 'filter', this.filterAll);
      this.listenTo(Todos, 'all', this.render);

      Todos.fetch();
    },
    filterAll: function(){
      Todos.each(this.filterOne, this);
    },

    filterOne: function(todo){
      todo.trigger('visible');
    },

    render: function(){
      var remaining = Todos.remaining().length;
      var completed = Todos.completed().length;

      if(Todos.length){
        this.$footer.show();
        this.$footer.html(this.template({
          completed: completed,
          remaining: remaining
        }))
      }else{
        this.$footer.hide();
      }

    },

    addOne: function( todo ){
      var view = new TodoView({model: todo});
      $('#todo-list').append(view.render().el);
    },
    addAll:function(){

    },

    createOnEnter: function( e ){
      if(e.which !== Common.ENTER_KEY ||
      !this.$input.val().trim() ){
        return ;
      }

      Todos.create( this.newAttributes() );
      this.$input.val('');
    },

    newAttributes: function(){
      return {
        title: this.$input.val().trim(),
        order: Todos.nextOrder(),
        completed: false
      }
    },

    clearCompleted: function(){

    },

    toggleAllComplete: function(){

    }
  });
  return AppView;
});